package com.yaowk.security;

import com.yaowk.common.api.StatusDict;
import com.yaowk.system.api.model.User;
import com.yaowk.system.server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserInfoService implements UserDetailsService {
    @Autowired
    private IUserService service;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = service.findByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (!user.getStatus().equals(StatusDict.TRUE)) {
            throw new DisabledException("账号不可用");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Long> permissions = service.findPermissionsByUserId(user.getId());
        for (Long permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.toString()));
        }
        return new UserInfo(authorities, user.getUsername(), user.getPassword(), user.getId());
    }
}
